/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-06-13 09:08:06
 * @LastEditTime: 2019-07-01 10:00:08
 * @LastEditors: Please set LastEditors
 */

import { config } from "../config.js"

class HTTP {
    // todo 添加全局loading
    request ({ url, data = {}, method = "POST", hastoken = 1 }) {
        let token = wx.getStorageSync('token')
        if (hastoken) {
            data.token = token
        }

        return new Promise((resolve, reject) => {
            wx.request({
                url: config.apiBaseUrl + url,
                method: method,
                data: data,
                header: {
                    'content-type': 'application/json',
                },
                success: res => {
                    // console.log(res,12);
                    
                    if (res.statusCode == 200) {
                        if (res.data.status == 0) {
                            resolve(res.data.data)
                        }
                        else if (res.data.status == 301) {
                            // 未登录 清除token和用户信息
                            wx.removeStorageSync("token")
                            wx.removeStorageSync("userinfo")

                            wx.showModal({
                                content: "请登录后再操作",
                                showCancel: false,
                                confirmText: "登录",
                                success: res => {
                                    if (res.confirm) {
                                        wx.navigateTo({
                                            url: '/pages/user/login/login'
                                        })
                                    }
                                }
                            })

                        }
                        else {
                            wx.showModal({
                                content: res.data.msg,
                            })
                        }
                    }
                    else {
                        // 服务器异常
                        reject();
                        console.log(res, "服务器异常");

                    }

                },
                fail: err => {
                    // api 调用失败
                    console.log(err, "err");


                },
                complate: res => {
                    console.log(res, "https");

                }
            })
        })



    }
}

export { HTTP }